#include "CreateTaskDialog.hpp"
#include <spdlog/spdlog.h>
#include <stdexcept>
#include "CheckURLSpecialSymbol.hpp"

CreateTaskDialog::CreateTaskDialog(Gtk::Window* parent)
{
  refBuilder=Gtk::Builder::create();
  try
  {
    refBuilder->add_from_file("CreateTaskUI.ui");
  }
  catch(const Glib::FileError & ex)
  {
    spdlog::error("CreateTaskUI FileError: {}",ex.what());
    throw;
  }
  catch(const Glib::MarkupError& ex)
  {
    spdlog::error("CreateTaskUI MarkupError: {}",ex.what());
    throw;
  }
  catch(const Gtk::BuilderError& ex)
  {
    spdlog::error("CreateTaskUI BuilderError: {}",ex.what());
    throw;
  }
  pDialog=refBuilder->get_widget<Gtk::Window>("mainWindow");
  if(!pDialog)
    throw std::runtime_error("无法加载CreateTaskUI主窗口");
  if(parent!=nullptr)
  {
    pDialog->set_transient_for(*parent);
    pDialog->set_destroy_with_parent(true);
    pDialog->set_modal();
    pDialog->set_hide_on_close();
  }

  auto pBtnOK=refBuilder->get_widget<Gtk::Button>("btnOK");
  if(!pBtnOK)
    throw std::runtime_error("无法加载btnOK元件");
  pBtnOK->signal_clicked().connect([this](){on_btnOK_click();});

  pEntryTaskName=refBuilder->get_widget<Gtk::Entry>("taskName");
  if(!pEntryTaskName)
    throw std::runtime_error("无法加载taskName元件");
  
  auto pBtnCancel=refBuilder->get_widget<Gtk::Button>("btnCancel");
  if(!pBtnCancel)
    throw std::runtime_error("无法加载btnCancel元件");
  pBtnCancel->signal_clicked().connect([this](){on_btnCancel_click();});

  pLabInfo=refBuilder->get_widget<Gtk::Label>("labInfo");
  if(!pLabInfo)
    throw std::runtime_error("无法加载labInfo元素");
}

CreateTaskDialog::~CreateTaskDialog()
{
  delete pDialog;
}


bool CreateTaskDialog::GetSuccessStatus()
{
  return successStatus;
}

std::string CreateTaskDialog::GetTaskName()
{
  return pEntryTaskName->get_text();
}

void CreateTaskDialog::on_btnCancel_click()
{
  pDialog->set_visible(false);
}

void CreateTaskDialog::on_btnOK_click()
{
  if(CheckSpectialSymbol(pEntryTaskName->get_text()))
  {
    successStatus=true;
    pDialog->set_visible(false);
  }
  else
    pLabInfo->set_text("输入的名称中不能包含特殊字符");
}

void CreateTaskDialog::Show()
{
  successStatus=false;
  pDialog->set_visible(true);
}

void CreateTaskDialog::test_call(Glib::RefPtr<Gtk::Application> app)
{
  app->add_window(*pDialog);
  pDialog->set_visible(true);
}

void CreateTaskDialog::signal_result_connect(const sigc::slot<void()> & solt)
{
  pDialog->signal_hide().connect(solt);
}
